package com.glodon.paas.document.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.FormParam;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.glodon.paas.account.api.bean.User;
import com.glodon.paas.consts.StringConst;
import com.glodon.paas.document.api.bean.File;
import com.glodon.paas.document.service.FileService;
import com.glodon.paas.document.service.ShareService;
import com.glodon.paas.document.service.util.DocumentUtil;
import com.glodon.paas.document.web.util.SecurityUtils;
import com.glodon.paas.exception.PaasServerException;

@Controller
@RequestMapping("/share")
public class ShareController {

    public static final Logger     LOGGER = LoggerFactory.getLogger(ShareController.class);

    @Autowired
    private ShareService           shareService;

    @Autowired
    private FileService            fileService;

    @Autowired
    private ActivityPublisher activityPublisher;

    @RequestMapping(value = "/do", method = RequestMethod.POST)
    public void shareFile(@FormParam("fileId")
    String fileId, @FormParam("email")
    String email, @FormParam("privilege")
    String privilege, @FormParam("accountName")
    String accountName, ModelMap model, HttpServletRequest request) throws PaasServerException {
        User use = SecurityUtils.getCurrentUser();
        File file = fileService.getFile(use.getId(), fileId, false);
        
        if (StringUtils.isBlank(accountName)) {
            accountName = email;
        }
        List<String> failedItems = new ArrayList<String>();
        List<User> successItems = new ArrayList<User>();
        String[] an = accountName.split(",");
        for (String account : an) {
            try {
                successItems.add(shareService.shareFile(use.getId(), fileId, account, privilege));
            } catch (PaasServerException e) {
                LOGGER.error(e.getMessage(), e);
                failedItems.add(account);
            }
        }
        model.addAttribute(StringConst.SUCCESS_ITEMS, successItems);
        model.addAttribute(StringConst.FAILED_ITEMS, failedItems);
        model.addAttribute(StringConst.RESULT, StringConst.SUCCESS);
        
        // Attivity
        activityPublisher.shareFile(use.getId(), use.getDisplayName(), fileId, file.getName(), successItems, true);
    }

    @RequestMapping(value = "/undo", method = RequestMethod.POST)
    public void undoShareFile(@FormParam("fileId")
    String fileId, @FormParam("userId")
    String userId, ModelMap model) throws PaasServerException {
        shareService.cancelShare(SecurityUtils.getCurrentUser().getId(), fileId, userId);
        model.addAttribute(StringConst.RESULT, StringConst.SUCCESS);
    }

    @RequestMapping(value = "/cancelShare", method = RequestMethod.POST)
    public void cancelShareFile(@FormParam("fileId")
    String fileId, ModelMap model) throws PaasServerException {
        String userId = SecurityUtils.getCurrentUser().getId();
        if (StringUtils.isNotEmpty(fileId)) {
            List<String> failedItems = new ArrayList<String>();
            String[] ids = fileId.split(StringConst.SEPARATOR_COMMA);
            for (String id : ids) {
                try {
                    shareService.cancelShare(userId, id);
                } catch (Exception e) {
                    failedItems.add(id);
                }
            }
            if (!failedItems.isEmpty()) {
                model.addAttribute(StringConst.FAILED_ITEMS, failedItems);
            }
        }
        model.addAttribute(StringConst.RESULT, StringConst.SUCCESS);
    }

    @RequestMapping(value = "/publish", method = RequestMethod.POST)
    public void publish(@FormParam("fileId") String fileId, ModelMap model) {
        User currentUser = SecurityUtils.getCurrentUser();
        String token = shareService.publish(currentUser.getId(), fileId);
        model.addAttribute(StringConst.PUBLIC_TOKEN, token);
        model.addAttribute(StringConst.RESULT, DocumentUtil.generatePublicURL(token));

        File file = fileService.getFile(currentUser.getId(), fileId, false);
        if (file != null) {
            activityPublisher.publishFile(currentUser.getId(), currentUser.getDisplayName(), file.getId(), file.getName(), token,true);
        }
    }

    @RequestMapping(value = "/cancelPublish", method = RequestMethod.POST)
    public void cancelPublish(@FormParam("fileId")
    String fileId, ModelMap model) {
        shareService.cancelPublish(SecurityUtils.getCurrentUser().getId(), fileId);
        model.addAttribute(StringConst.RESULT, StringConst.SUCCESS);
    }

    @RequestMapping(value = "/listByMe", method = RequestMethod.GET)
    public void listByMe(@RequestParam(value = "id", required = false)
    String fileId, @RequestParam(value = "root", required = false)
    String root, @RequestParam(value = "orderBy", required = false, defaultValue = "updateTime")
    String orderBy, @RequestParam(value = "orderType", required = false)
    String orderType, ModelMap model) throws PaasServerException {

        String userId = SecurityUtils.getCurrentUser().getId();
        List<File> files;
        if (StringUtils.isEmpty(fileId)) {
            files = shareService.getFilesByShares(shareService.getSharesByMe(userId), orderBy, orderType, true);
            model.addAttribute(StringConst.PATH, "/");
        } else {
            files = fileService.getFiles(userId, orderBy, orderType, fileId, true);
            model.addAttribute(StringConst.PATH, shareService.getNavigationByMe(root, fileId));
        }
        model.addAttribute(StringConst.ITEMS, files);
    }

    @RequestMapping(value = "/listForMe", method = RequestMethod.GET)
    public void listForMe(@RequestParam(value = "id", required = false)
    String fileId, @RequestParam(value = "orderBy", required = false, defaultValue = "updateTime")
    String orderBy, @RequestParam(value = "orderType", required = false)
    String orderType, ModelMap model) throws PaasServerException {
        String userId = SecurityUtils.getCurrentUser().getId();
        List<File> files;
        if (StringUtils.isEmpty(fileId)) {
            files = shareService.getFilesByShares(shareService.getSharesForMe(SecurityUtils.getCurrentUser().getId()),
                                                  orderBy, orderType, true);
            model.addAttribute(StringConst.PATH, "/");
        } else {
            files = fileService.getFiles(userId, fileId, orderBy, orderType, true);
            model.addAttribute(StringConst.PATH, shareService.getNavigationForMe(userId, fileId));
        }
        model.addAttribute(StringConst.ITEMS, files);
    }

    @RequestMapping(value = "/listPublic", method = RequestMethod.GET)
    public void listPublic(@RequestParam(value = "id", required = false)
    String fileId, @RequestParam(value = "orderBy", required = false, defaultValue = "updateTime")
    String orderBy, @RequestParam(value = "orderType", required = false)
    String orderType, ModelMap model) throws PaasServerException {
        String userId = SecurityUtils.getCurrentUser().getId();
        List<File> files;
        if (StringUtils.isEmpty(fileId)) {
            files = shareService.getFilesByShares(shareService.getPublicShares(SecurityUtils.getCurrentUser().getId()),
                                                  orderBy, orderType, true);
            model.addAttribute(StringConst.PATH, "/");
        } else {
            files = fileService.getFiles(userId, fileId, orderBy, orderType, true);
            model.addAttribute(StringConst.PATH, shareService.getNavigationByMe(userId, fileId));
        }
        model.addAttribute(StringConst.ITEMS, files);
    }

    @RequestMapping(value = "/shareInfo", method = RequestMethod.GET)
    public void getSharedInfo(@FormParam("fileId")
    String fileId, ModelMap model) {
        if (StringUtils.isNotEmpty(fileId)) {
            List<User> users = shareService.getSharedUser(SecurityUtils.getCurrentUser().getId(), fileId);
            model.addAttribute(StringConst.USERS, users);
        }
    }
}
